<template>
  <div v-show="visible">
    <el-dialog class="printDialog" title="打印预览" width="80%"
               :visible.sync="visible"
               :append-to-body="true"
    >
      <iframe ref="win" class="printDialogFrame" src="print.html"></iframe>
      <template slot="footer">
        <el-button size="small" type="primary" @click="handleOk">
          确定
        </el-button>
      </template>
    </el-dialog>
    <iframe v-if="print" ref="win" class="printDialogFrame" src="print.html"></iframe>
  </div>
</template>

<script>
export default {
  name: 'printDialog',
  data() {
    return {
      visible: false,
      print: false
    }
  },
  watch: {
    visible() {
      // if (!this.visible) {
      //   const doc = this.R.path(['contentWindow', 'document'], this.$refs.win)
      //
      //   if (!this.R.isNil(doc)) {
      //     const body = doc.querySelector('body')
      //
      //     if (!this.R.isNil(body)) {
      //       body.innerHTML = ''
      //     }
      //   }
      // }
    }
  },
  methods: {
    openPrintDialog(showPreviewFunc, print = false) {
      if (this.R.isNil(showPreviewFunc)) {
        return
      }
      this.print = print

      if (!this.print) {
        this.visible = true
      }
      this.$nextTick(() => {
        const wind = this.$refs.win.contentWindow

        if (this.R.isNil(wind)) {
          return
        }
        // wind.document.body.innerText = ''

        setTimeout(() => {
          showPreviewFunc(wind)
          wind.print()
        }, 200)
      })
    },
    handleOk() {
      this.visible = false
    }
  },
  mounted() {
    this.$vBus.$on('SHOW_PRINT_DIALOG', this.openPrintDialog)
  },
  beforeDestroy() {
    this.$vBus.$off('SHOW_PRINT_DIALOG', this.openPrintDialog)
  }
}
</script>

<style>
.printDialog .el-dialog__body {
  padding: 0;
  height: 600px;
}
</style>

<style scoped>
.printDialogFrame {
  width: 100%;
  height: 100%;
  border: 0;
}
</style>
